var SelectTool = function(){
	var env = {};
	var config = {
		status: 0, //0表示关闭选择模式，1表示开启选择模式
		multi: 0 //0表示单选模式，1表示多选模式
	}
	var current_selectors;
	var my_selector_generator = new CssSelectorGenerator;
	
	var createPanel = function(){
		if($('#papaSettingPanel').is()){
			return;
		}
		var html = [];
		//selector panel
		html.push("<div id='papaSettingPanel'>");
		html.push("<input type='text' id='papa-selector-field'>")
		html.push("<button id='papaStartBtn'>开始选择</button>");
		html.push("<button id='papaClearBtn'>清除所选</button>");
		html.push("<button id='papaUp'>向外(←)</button>");
		html.push("<button id='papaDown'>向内(→)</button>");
		html.push("<button id='papaLeft'>向前(↑)</button>");
		html.push("<button id='papaRight'>向后(↓)</button>");
		html.push("</div>");
		$('body').append(html.join(''));
	}
	
	
	var initUI = function(){
		createPanel();
		$('#papaSettingPanel').hide(); // exclude
		$("body :visible").mouseover(function(event){
			if(config.status){
				event.preventDefault();
				event.stopPropagation();
				$(".papa-hover").removeClass('papa-hover');
				if(!$(this).hasClass('papa-selected')){
					$(this).addClass('papa-hover');
				}
			}
		}).mouseout(function(event){
			if(config.status){
				event.preventDefault();
				event.stopPropagation();
				$(this).removeClass('papa-hover');
			}
		}).click(function(event){
			if(config.status){
				event.preventDefault();
				event.stopPropagation();
				var me = $(this);
				me.removeClass('papa-hover');
				
				if(config.multi == 0 && current_selectors){
					$('.papa-selected').removeClass('papa-selected');
					$('#papa-selector-field').val('');
					current_selectors = null;
				}
				
				var selectors = getSelectors(this, document.querySelectorAll('.papa-selected'));
				if(selectors){
					current_selectors = selectors;
					var sel = selectors.join(' > ');
					$(sel).addClass('papa-selected');
					$('#papa-selector-field').val(sel);
				}else{
					console.log('selection not valid');
				}
			}
		});
		
		$('#papaUp').click(function(){
			if(config.status){
				if(current_selectors.length == 1 && current_selectors[0] == 'body'){
					return;
				}
				var ele = clearSelected();
				var p = ele.parent();
				if(p[0] == document.body){
					$('.papa-selected').removeClass('papa-selected');
					p.addClass('papa-selected');
					$('#papa-selector-field').val('body');
					current_selectors = ['body'];
				}else{
					ele.parent().click();
				}
			}
		})
		$('#papaDown').click(function(){
			if(config.status){
				var ele = $('.papa-selected');
				var t = ele.children().first();
				if(t.length){
					current_selectors = null;
					ele.removeClass('papa-selected');
					t.click();
				}
			}
		})
		$('#papaLeft').click(function(){
			if(config.status){
				var ele = clearSelected();
				while(true){
					var t = ele.prev();
					if(t.length){
						t.click();
						break;
					}else{
						ele = ele.parent();
					}
				}
			}
		})
		$('#papaRight').click(function(){
			if(config.status){
				var ele = clearSelected();
				while(true){
					var t = ele.next();
					if(t.length){
						t.click();
						break;
					}else{
						ele = ele.parent();
					}
				}
			}
		})
		$('#papaClearBtn').click(function(){
			clearSelected();
		})
		
		$('#papaStartBtn').click(function(){
			if(config.status == 0){
				config.status = 1;
				$(this).text("结束选择");
			}else{
				config.status = 0;
				$(this).text("开始选择");
				if(config.multi == 0){
					var selector = finishSelect();
					chrome.runtime.sendMessage({
						cmd: 'endSelect',
						params: {
							selector: selector
						}
					});
				}
			}
		})
		
		$(window).keydown(function(ev){
			if(config.status == 1){
				ev.preventDefault();
				ev.stopPropagation();
				var k = ev.which;
				if(k == 37){
					$('#papaUp').click();
				}
				else if(k == 39){
					$('#papaDown').click();
				}
				else if(k == 38){
					$('#papaLeft').click();
				}
				else if(k == 40){
					$('#papaRight').click();
				}
				else if(k == 46){
					$('#papaClearBtn').click();
				}
				else if(k == 13){
					$('#papaStartBtn').click();
				}
			}
		})
	}
	
	var applyConfig = function(){
		if(config.status == 1){
			$('#papaStartBtn').text("结束选择");
		}else{
			clearSelected();
			$('#papaStartBtn').text("开始选择");
		}
	}
	
	var startSelect = function(_config){
		config.status = 1;
		applyConfig();
		$.extend(config, _config);
		//apply config
		//TODO
		$('#papaSettingPanel').show();
	}
	
	var finishSelect = function(){
		$('#papaSettingPanel').hide();
		config.status = 0;
		var selector = current_selectors && current_selectors.join(' > ');
		clearSelected();
		return selector;
	}
	
	var clearSelected = function(){
		current_selectors = null;
		$("#papa-selector-field").val('');
		var ele = $('.papa-selected').removeClass('papa-selected');
		return ele;
	}
	
	var getSelectors = function(element, selectedElements){
		if(current_selectors){
			var selectors = _testByRemoveNthTypeOf(current_selectors, [element]);
			if(!selectors){
				var s = my_selector_generator.getSelector(element);
				selectors = _testByRemoveNthTypeOf(s, selectedElements);
			}
			return selectors
		}
		return my_selector_generator.getSelector(element);
	}
	
	var _testSelectors = function(elements, selector){
		var queried = document.querySelectorAll(selector.join(' > '));
		for (var i = 0; i < elements.length; i++) {
			var found = false;
			for (var j = 0; j < queried.length; j++) {
				if(queried[j] == elements[i]){
					found = true;
					break;
				}
			}
			if(found === false){
				return false;
			}
		}
		return true;
	}
	
	var _testByRemoveNthTypeOf = function(selectors, elements){
		var len = selectors.length;
		var start = -1;
		while(start < len - 1){
			var found = false;
			var testSelectors = [];
			for (var i = 0; i < len; i++) {
				var s1 = selectors[len - 1 - i];
				if(i > start && found === false){
					start = i;
					var x = s1.indexOf(':nth-of-type');
					if(x != -1){
						found = true;
						s1 = s1.substring(0, x);
					}
				}
				testSelectors.push(s1);
			}
			if(found === true){
				var matched = _testSelectors(elements , testSelectors.reverse());
				if(matched){
					return testSelectors
				}
			}
		}
		return null;
	}
	
	chrome.runtime.onMessage.addListener(function(msg, _, callback){
		if(msg.cmd == 'startSelect'){
			startSelect(msg.params);
		}
		else if(msg.cmd == 'startScrape'){
			new Scraper(msg.params);
		}
	});
	
	initUI();
}
